package com.example.yk_fx;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.yk_fx.adapter.GiftAdapter;
import com.example.yk_fx.adapter.MessAdapter;
import com.example.yk_fx.base.BaseActivity;
import com.example.yk_fx.databinding.ActivityLiveBinding;
import com.example.yk_fx.db.Account;
import com.example.yk_fx.db.DataBaseUtil;
import com.example.yk_fx.entity.GiftEntity;
import com.example.yk_fx.entity.MessageEntity;
import com.example.yk_fx.entity.VideoEntity;
import com.example.yk_fx.live.GiftControl;
import com.example.yk_fx.live.LiveViewModel;
import com.example.yk_fx.pay.PayActivity;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseActivity<ActivityLiveBinding, LiveViewModel> {
    VideoEntity.DataBean video;
    List<GiftEntity.DataBean> gifts = new ArrayList<>();
    GiftAdapter giftAdapter;
    int giftIndex = -1;
    private GiftControl giftControl;


    private Account account;


    List<MessageEntity> list = new ArrayList<>();
    MessAdapter messAdapter;
    private DanmakuContext danmakuContext;
    private BaseDanmakuParser parser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };
    @Override
    protected int bindLayout() {
        return R.layout.activity_live;
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected void initView() {
        //初始化  让视频播放起来
        video = (VideoEntity.DataBean) getIntent().getExtras().get("video");
        initGsy();//让视频播放起来
        initGift();//加载礼物列表
        initMoney();//初始化余额
        initMess();//初始化消息列表
        initDanmu();//初始化弹幕
        giftControl = new GiftControl(vdb.giftview);
        vdb.love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vdb.ksg.addLikeImages(R.mipmap.ic_launcher,R.mipmap.ic_launcher_round);
                vdb.ksg.addFavor();
            }
        });
        vdb.gift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vdb.clGift.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(LiveActivity.this, R.anim.aa);
                animation.setInterpolator(new BounceInterpolator());
                vdb.clGift.startAnimation(animation);
            }
        });
        //点击发送礼物
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                giftIndex = position;//下标赋值，
            }
        });
        vdb.btnGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGift();
            }
        });
        //点击跳转到充值界面
        vdb.gomoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(LiveActivity.this,PayActivity.class),200);
            }
        });
        vdb.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //输入框显示
                vdb.clEt.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(LiveActivity.this, R.anim.aa);
                vdb.clEt.startAnimation(animation);
                vdb.et.requestFocus();//输入框获取焦点
            }
        });
        //点击发送按钮，实现发送消息
        vdb.etSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = vdb.et.getText().toString().trim();//trim去掉字符串前后空格
                if(string.isEmpty()){
                    ToastUtils.showLong("您未输入任何有效文字");
                    return;
                }
                //
                list.add(new MessageEntity(string,"123"));
                messAdapter.notifyDataSetChanged();

                vdb.et.setText("");
                vdb.clEt.setVisibility(View.GONE);
                vdb.messageRv.scrollToPosition(list.size()-1);

                vdb.danmu.enableDanmakuDrawingCache(false);
                vdb.danmu.removeAllDanmakus(true);
                vdb.danmu.clear();

                BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
                danmaku.text = string;
                danmaku.textColor = R.color.purple_500;
                danmaku.borderColor = R.color.teal_200;
                danmaku.textSize = 60;


                vdb.danmu.addDanmaku(danmaku);
                vdb.danmu.start();//开始显示弹幕
            }
        });
    }

    private void initDanmu() {
        vdb.danmu.enableDanmakuDrawingCache(false);
        vdb.danmu.removeAllDanmakus(true);
        vdb.danmu.clear();
        danmakuContext = DanmakuContext.create();

        vdb.danmu.prepare(parser,danmakuContext);
    }

    private void initMess() {
        messAdapter = new MessAdapter(R.layout.item_mess,list);
        vdb.messageRv.setAdapter(messAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);//列表会从最后开始，依次向上移动    //不加的话，默认是依次向下移动
        vdb.messageRv.setLayoutManager(linearLayoutManager);

    }

    private void initMoney() {
        //先判断有没有
        account = DataBaseUtil.getInstance().getAccountDao().queryAccount("123");
        if(account==null){
            account = new Account("123",0);
            DataBaseUtil.getInstance().getAccountDao().insertAccount(account);
        }
        vdb.gomoney.setText(account.getPay()+"元");
    }

    private void sendGift() {
        if(giftIndex<0){
            ToastUtils.showLong("未选中礼物");
            return;
        }
        giftControl.giftShow(gifts.get(giftIndex));
        //展示礼物动画
        vdb.ivGift.setVisibility(View.VISIBLE);//显示出来，然后添加动画效果
        Glide.with(this).load(gifts.get(giftIndex).getGiftpath()).into(vdb.ivGift);//显示选中的礼物

        int width = getWindowManager().getDefaultDisplay().getWidth();//模拟器屏幕宽度
        int height = getWindowManager().getDefaultDisplay().getHeight();//模拟器屏幕高度
        ObjectAnimator animator = ObjectAnimator.ofFloat(vdb.ivGift, "translationX", 0, width, width / 2 - 75).setDuration(2000);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(vdb.ivGift, "translationY", 0, height, height / 2 + 75).setDuration(2000);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(vdb.ivGift, "rotation", 0, 720).setDuration(1000);
        AnimatorSet set = new AnimatorSet();
        set.play(animator).with(animator1).before(rotation);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                vdb.ivGift.setVisibility(View.GONE);//隐藏起来
            }
        });
        set.start();

    }

    private void initGift() {
        giftAdapter = new GiftAdapter(R.layout.item_gift,gifts);
        vdb.rvGift.setAdapter(giftAdapter);
        vdb.rvGift.setLayoutManager(new GridLayoutManager(this,4));
        vm.getGift();
    }

    private void initGsy() {
        vdb.gsy.setUp(video.getVideopath(),true,"");
        vdb.gsy.getBackButton().setVisibility(View.GONE);
        vdb.gsy.startPlayLogic();
    }

    @Override
    protected void initData() {
        vm.success.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity entity) {
                gifts.clear();
                gifts.addAll(entity.getData());
                giftAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==200&&resultCode==201){
            initMoney();
        }
    }
}